package com.modifiertech.lineage.skills;

import com.feed_the_beast.ftblib.lib.icon.Icon;
import com.modifiertech.lineage.BaseConst;
import com.modifiertech.lineage.api.LineageModAccess;
import com.modifiertech.lineage.api.PlayerData;
import com.modifiertech.lineage.api.PlayerDataSkill;
import com.modifiertech.lineage.base.ConfigHandler;
import com.modifiertech.lineage.client.gui.ftbint.GuiIconsV2;
import com.modifiertech.lineage.effect.EffectApplier;
import com.modifiertech.lineage.event.PlayerDataHandler;
import com.modifiertech.lineage.event.SkillAnimateCallEvent;
import com.modifiertech.lineage.handler.PlayerManaModifyHandler;
import com.modifiertech.lineage.network.MessageClientSay;
import com.modifiertech.lineage.network.MessageClientSkillJumpSplash;
import com.modifiertech.lineage.network.NetworkHandler;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.SharedMonsterAttributes;
import net.minecraft.entity.ai.attributes.AttributeModifier;
import net.minecraft.entity.ai.attributes.IAttributeInstance;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.init.SoundEvents;
import net.minecraft.network.play.server.SPacketEntityVelocity;
import net.minecraft.util.DamageSource;
import net.minecraft.util.SoundCategory;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraftforge.event.entity.living.LivingFallEvent;
import net.minecraftforge.event.entity.living.LivingHurtEvent;
import net.minecraftforge.fml.common.gameevent.TickEvent;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**跳劈
 * 
 */
public class JumpSplash extends PlayerDataSkill {
    @Override
    protected Icon defineSkillIcon() {
        return GuiIconsV2.JumpSplash;
    }

    @Override
    protected String defineSkillType() {
        return BaseConst.PLAYER_ADV_TAG__SKILLS_SPE;
    }

    @Override
    protected String defineSkillSecondType() {
        return BaseConst.PLAYER_ADV_SEC_TAG__SKILLS_ONCE;
    }

    @Override
    protected String defineSkillName() {
        return "跳劈";
    }

    @Override
    protected int defineSkillLevelDependency() {
        return 5;
    }

    @Override
    public String defineSkillDesc() {
        int skillLevel = getSkillLevel();
        return "角色跃向空中，对目标发动强力劈砍\n§4§l[变种:践踏]按下右键时发动,将在原地进行践踏"+
                (skillLevel>0?"\n效果: 落下时造成 §6§l"+getLevelDamage()+" 伤害,眩晕 §6§l3 秒.":"") ;
    }

    @Override
    protected double defineSkillRowX() {
        return 3;
    }

    @Override
    protected double defineSkillColumnY() {
        return 1;
    }

    @Override
    protected int defineSkillCoolDown() {
        return ConfigHandler.skillJumpSplashCoolDown;
    }

    @Override
    protected double defineSkillManaUse() {
        return 3.0d;
    }

    @Override
    protected List<String> defineSkillDependencyName() {
        return new ArrayList<>();
    }

    @Override
    protected int defineSkillRegion() {
        return 0;
    }

    @Override
    protected int defineUpgradePoint() {
        return 1;
    }

    @Override
    public void onSkillAnimateCall(SkillAnimateCallEvent.Post event) {
        //此处为playerMP端 playerData
        PlayerData playerData = PlayerDataHandler.get(event.getEntityPlayer());
        //检查当前技能是否可用(是否处于CD 等)
        if (!playerData.checkOnceTypeSkillAvailable(getSkillName())) return;
        if (!playerData.checkSkillCdAvailable(getSkillName())){
            return;
        }
        if (!playerData.checkSkillManaAvailable(defineSkillManaUse())){
            //触发特定客户端通知
            NetworkHandler.INSTANCE.sendTo(new MessageClientSay().write("魔力不足!"), (EntityPlayerMP) event.getEntityPlayer());
            return;
        }

            EntityPlayerMP playerMP = (EntityPlayerMP) event.getEntityPlayer();
            float forwardFactor = 1.5f;
            playerMP.motionY = 0.85;//向上跳跃的力量.
            //增强:原地触发
            if (event.getEnhance()){
                forwardFactor = 0f; // 向前推进的力量
                playerMP.motionY=0;
            }

            playerMP.motionX -= Math.sin(Math.toRadians(playerMP.rotationYaw)) * forwardFactor;
            playerMP.motionZ += Math.cos(Math.toRadians(playerMP.rotationYaw)) * forwardFactor;

            // 立即更新玩家的位置和速度
            playerMP.velocityChanged = true;
            //设置击退抗性.

            IAttributeInstance knockbackResistance = playerMP.getAttributeMap()
                .getAttributeInstance(SharedMonsterAttributes.KNOCKBACK_RESISTANCE);

            // 定义一个击退抗性修饰符，值为 1.0 表示完全免疫击退
            AttributeModifier knockbackModifier =
                new AttributeModifier("NoKnockbackModifier", 1.0, 0);

            // 应用击退抗性修饰符
            if (!knockbackResistance.hasModifier(knockbackModifier)) {
             knockbackResistance.applyModifier(knockbackModifier);
            }


            playerData.turnOnSkillExecutedDelay(getSkillName(), 5);
            //扣减魔法
            PlayerManaModifyHandler.INSTANCE.manaModify(event.getEntityPlayer(),0-defineSkillManaUse(),playerData);
            //设定技能cd
            playerData.setSkillCdAndSync(getSkillName(),defineSkillCoolDown(),playerMP);
    }


    @Override
    public void onPlayerTick(TickEvent.PlayerTickEvent event) {
        PlayerData playerData = PlayerDataHandler.get(event.player);
        //检查技能执行状态
        if (playerData.checkSkillExecuted(getSkillName())) {
            //落地处理
            Optional<EntityPlayerMP> entityPlayerMP = LineageModAccess.getPlayerMpFromEntityPlayer(event.player
                    , true);
            // 玩家落地，触发爆炸效果
            if (entityPlayerMP.isPresent()) {
                EntityPlayerMP playerMP = entityPlayerMP.get();
                if (event.player.onGround) {
                    //清除额外击退抗性.
                    IAttributeInstance knockbackResistance = playerMP.getAttributeMap().getAttributeInstance(SharedMonsterAttributes.KNOCKBACK_RESISTANCE);

                    AttributeModifier knockbackModifier =
                            new AttributeModifier("NoKnockbackModifier", 1.0, 0);

                    // 移除击退抗性修饰符
                    if (knockbackResistance.hasModifier(knockbackModifier)) {
                        knockbackResistance.removeModifier(knockbackModifier);
                    }



                    playerMP.connection.sendPacket(new SPacketEntityVelocity(playerMP.getEntityId(), 0, -0.1, 0));                    playerMP.fallDistance = 0f;
//                    playerMP.velocityChanged = true; // 确保速度变化生效

                    playerMP.world.createExplosion(playerMP, playerMP.posX, playerMP.posY, playerMP.posZ, 0.0F, false);
                    playerMP.world.playSound(null, playerMP.posX, playerMP.posY, playerMP.posZ,
                            SoundEvents.ENTITY_GENERIC_EXPLODE, SoundCategory.PLAYERS, 1.0F, 1.0F);

                    //生成环状粒子
                    //第一段: 服务端造成伤害
                    triggerGroundSmashDamage(playerMP);
                    //第二段: 客户端渲染例子
                    NetworkHandler.INSTANCE.sendTo(new MessageClientSkillJumpSplash().write(playerMP.getPosition())
                            ,playerMP);

                    //技能设置为触发结束
                    playerData.turnOffSkillExecuted(getSkillName());
                    //技能设置为首tick执行为假
                    playerData.setSkillTickOnce(getSkillName(),false);
                } else {
                    if (!playerData.checkSkillTickOnce(getSkillName())){
                        //快速下坠
                        playerMP.connection.sendPacket(new SPacketEntityVelocity(playerMP.getEntityId(), 0, -1.7, 0));
//                        playerMP.velocityChanged = true;
                        playerData.setSkillTickOnce(getSkillName(),true);
                    }
                }
            }
        }
    }

    /**造成范围伤害
     *
     * @param player
     */
    public void triggerGroundSmashDamage(EntityPlayerMP player){
        // 粒子效果的半径
        double radius = 3.0;
        // 获取玩家的位置
        BlockPos playerPos = player.getPosition();
        //效果范围盒
        AxisAlignedBB boundingBox = new AxisAlignedBB(
                playerPos.getX() - radius, playerPos.getY() - 1, playerPos.getZ() - radius,
                playerPos.getX() + radius, playerPos.getY() + 3, playerPos.getZ() + radius
        );
        // 获取包围盒内的所有生物
        for (Entity entity : player.getServerWorld().getEntitiesWithinAABBExcludingEntity(player, boundingBox)) {
            if (entity instanceof EntityLivingBase) {
                EntityLivingBase livingEntity = (EntityLivingBase) entity;
                EffectApplier.applyStun(livingEntity,60,0);
                // 对生物造成3点伤害
                livingEntity.attackEntityFrom(DamageSource.causePlayerDamage(player), getLevelDamage());
            }
        }
    }



    @Override
    public void onLivingFallEvent(LivingFallEvent event) {
        PlayerData playerData = PlayerDataHandler.get((EntityPlayer) event.getEntityLiving());
        //检查技能执行状态
        if (playerData.checkSkillExecuted(getSkillName())) {
            event.setCanceled(true);
        }
    }

    @Override
    public void onHurt(LivingHurtEvent event) {
        PlayerData playerData = PlayerDataHandler.get((EntityPlayer) event.getEntityLiving());
        //检查技能执行状态
        if (playerData.checkSkillExecuted(getSkillName())) {
            event.setCanceled(true);
        }
    }

    private float getLevelDamage(){
        return new BigDecimal(3 + (2 * getSkillLevel()))
                .setScale(2, RoundingMode.HALF_UP)
                .floatValue();
    }



}
